/*
 * Copyright (c) 2024 坚果派
 * 
 * 公众号：nutpi
 * 电话：17752170152
 * 官网：https://www.nutpi.net/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import 'package:flutter/material.dart';
import 'package:flutter_digital_timer_depo/models/alarm.dart';

class AlarmEditScreen extends StatefulWidget {
  final Alarm? alarm; // 如果是编辑现有闹钟，则传入闹钟对象

  const AlarmEditScreen({Key? key, this.alarm}) : super(key: key);

  @override
  State<AlarmEditScreen> createState() => _AlarmEditScreenState();
}

class _AlarmEditScreenState extends State<AlarmEditScreen> {
  late TimeOfDay _selectedTime;
  late TextEditingController _labelController;
  late List<bool> _repeatDays;
  late AlarmInteractionType _interactionType;

  @override
  void initState() {
    super.initState();
    // 如果是编辑现有闹钟，则使用其属性，否则使用默认值
    _selectedTime = widget.alarm?.time ?? TimeOfDay.now();
    _labelController = TextEditingController(text: widget.alarm?.label ?? '');
    _repeatDays = widget.alarm?.repeatDays ?? List.filled(7, false);
    _interactionType = widget.alarm?.interactionType ?? AlarmInteractionType.tap;
  }

  @override
  void dispose() {
    _labelController.dispose();
    super.dispose();
  }

  // 保存闹钟
  void _saveAlarm() {
    final newAlarm = Alarm(
      id: widget.alarm?.id ?? DateTime.now().millisecondsSinceEpoch, // 如果是新闹钟，使用时间戳作为ID
      time: _selectedTime,
      label: _labelController.text,
      isEnabled: widget.alarm?.isEnabled ?? true,
      repeatDays: _repeatDays,
      interactionType: _interactionType,
    );

    Navigator.pop(context, newAlarm);
  }

  // 选择时间
  Future<void> _selectTime() async {
    final TimeOfDay? pickedTime = await showTimePicker(
      context: context,
      initialTime: _selectedTime,
    );

    if (pickedTime != null && pickedTime != _selectedTime) {
      setState(() {
        _selectedTime = pickedTime;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.alarm == null ? '添加闹钟' : '编辑闹钟'),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveAlarm,
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 时间选择
            Card(
              child: ListTile(
                title: const Text('时间'),
                subtitle: Text(
                  '${_selectedTime.hour.toString().padLeft(2, '0')}:${_selectedTime.minute.toString().padLeft(2, '0')}',
                  style: const TextStyle(fontSize: 24.0),
                ),
                trailing: const Icon(Icons.access_time),
                onTap: _selectTime,
              ),
            ),
            const SizedBox(height: 16.0),

            // 标签输入
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextField(
                  controller: _labelController,
                  decoration: const InputDecoration(
                    labelText: '标签',
                    hintText: '输入闹钟标签（可选）',
                    border: OutlineInputBorder(),
                  ),
                  maxLength: 30,
                ),
              ),
            ),
            const SizedBox(height: 16.0),

            // 重复日期选择
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '重复',
                      style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8.0),
                    Wrap(
                      spacing: 8.0,
                      children: [
                        _buildDayChip(0, '周一'),
                        _buildDayChip(1, '周二'),
                        _buildDayChip(2, '周三'),
                        _buildDayChip(3, '周四'),
                        _buildDayChip(4, '周五'),
                        _buildDayChip(5, '周六'),
                        _buildDayChip(6, '周日'),
                      ],
                    ),
                    const SizedBox(height: 8.0),
                    Wrap(
                      spacing: 8.0,
                      runSpacing: 8.0,
                      alignment: WrapAlignment.spaceEvenly,
                      children: [
                        SizedBox(
                          width: 140,
                          child: OutlinedButton(
                            onPressed: () {
                              setState(() {
                                _repeatDays = List.filled(7, true);
                              });
                            },
                            child: const Text('每天'),
                          ),
                        ),
                        SizedBox(
                          width: 140,
                          child: OutlinedButton(
                            onPressed: () {
                              setState(() {
                                _repeatDays = [true, true, true, true, true, false, false];
                              });
                            },
                            child: const Text('工作日'),
                          ),
                        ),
                        SizedBox(
                          width: 140,
                          child: OutlinedButton(
                            onPressed: () {
                              setState(() {
                                _repeatDays = [false, false, false, false, false, true, true];
                              });
                            },
                            child: const Text('周末'),
                          ),
                        ),
                        SizedBox(
                          width: 140,
                          child: OutlinedButton(
                            onPressed: () {
                              setState(() {
                                _repeatDays = List.filled(7, false);
                              });
                            },
                            child: const Text('不重复'),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16.0),

            // 交互方式选择
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '交互方式',
                      style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8.0),
                    RadioListTile<AlarmInteractionType>(
                      title: const Text('轻按'),
                      subtitle: const Text('轻按闹钟项目切换状态'),
                      value: AlarmInteractionType.tap,
                      groupValue: _interactionType,
                      onChanged: (value) {
                        setState(() {
                          _interactionType = value!;
                        });
                      },
                    ),
                    RadioListTile<AlarmInteractionType>(
                      title: const Text('双击'),
                      subtitle: const Text('双击闹钟项目切换状态'),
                      value: AlarmInteractionType.doubleTap,
                      groupValue: _interactionType,
                      onChanged: (value) {
                        setState(() {
                          _interactionType = value!;
                        });
                      },
                    ),
                    RadioListTile<AlarmInteractionType>(
                      title: const Text('长按'),
                      subtitle: const Text('长按闹钟项目切换状态'),
                      value: AlarmInteractionType.longPress,
                      groupValue: _interactionType,
                      onChanged: (value) {
                        setState(() {
                          _interactionType = value!;
                        });
                      },
                    ),
                    RadioListTile<AlarmInteractionType>(
                      title: const Text('滑动'),
                      subtitle: const Text('左滑切换状态，右滑删除'),
                      value: AlarmInteractionType.swipe,
                      groupValue: _interactionType,
                      onChanged: (value) {
                        setState(() {
                          _interactionType = value!;
                        });
                      },
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建日期选择芯片
  Widget _buildDayChip(int index, String label) {
    return FilterChip(
      label: Text(label),
      selected: _repeatDays[index],
      onSelected: (selected) {
        setState(() {
          _repeatDays[index] = selected;
        });
      },
      selectedColor: Theme.of(context).colorScheme.primary.withOpacity(0.3),
    );
  }
}